use redis::{Client, AsyncCommands};

pub struct RedisConnector {
    client: Client,
}

impl RedisConnector {
    pub fn new(redis_url: &str) -> Self {
        Self {
            client: Client::open(redis_url).expect("Redis连接失败")
        }
    }
    pub async fn generate_code(&self, ttl: usize) -> String {
        let mut conn = self.client.get_async_connection().await.unwrap();
        let code = nanoid::nanoid!(6);
        conn.set_ex(&code, "pending", ttl).await.unwrap();
        code
    }

    pub async fn validate_code(&self, code: &str) -> bool {
        let mut conn = self.client.get_async_connection().await.unwrap();
        conn.exists(code).await.unwrap_or(false)
    }
}